
Imports System.Runtime.Serialization
Imports System.Drawing
Imports System.Drawing.Drawing2D
Imports cmplib01
Imports FMPLib01

Public Class frmCampaignRunner
    Inherits System.Windows.Forms.Form

    Const c_Module As String = "Campaigner"
    Const c_COMBATPHASES As Integer = 50

    Private Enum EnablementLevel
        NoneEnable = 0
        GameLoaded = 1
        PlayerLoggedIn = 2
        PlayerLoggedOut = 3
        UnitSelected = 4
        ModeratorLoggedIn = 5
        PlayerLoggedInCombatTurn = 6  ' you can't set waypoints but you can see where combats will occur.
    End Enum

    Private Enum DisplayIconSize
        LargeIcon = 0
        MediumIcon = 1
        SmallIcon = 2
    End Enum

    Private Enum TurnMode
        NormalTurn = 0
        CombatTurn = 1
    End Enum

    Private GameTitle As String
    Private CurrentGame As New CampaignerGameData()
    Private GameLoaded As Boolean
    Private bchitSelected As Boolean
    Private mTurnMode As TurnMode = TurnMode.NormalTurn
    Private ptrSelectedBattle As Battle
    Private stopReplay As Boolean = True

    Private WithEvents newTurnGrinder As New CampaignerCombatEngine.CampaignerCombatEngineB

    Private m_DisplayIconMode As DisplayIconSize = DisplayIconSize.LargeIcon
    Private m_DeployUnit As Boolean
    Friend WithEvents fmvMap As CTest.ctlCampaignerMapControl
    Friend WithEvents btnVictory As System.Windows.Forms.Button
    Private m_ToolBarEnablementLevel As EnablementLevel = EnablementLevel.NoneEnable


#Region " Windows Form Designer generated code "

    Public Sub New()
        MyBase.New()

        Try
            'This call is required by the Windows Form Designer.
            InitializeComponent()
        Catch ex As Exception
            HandleException("frmCampaignRunner.New", ex)
        End Try

        'Add any initialization after the InitializeComponent() call
        'fmvMap2.ShowLabels = True
        'fmvMap2.ShowLOS = True
        'fmvMap2.ShowZOC = True
        'fmvMap2.ShowDeploymentZones = True
        'fmvMap2.ShowWaypoints = True
        'fmvMap2.PhaseCount = 50

        GameTitle = "Campaigner"

        tmrReplay.Interval = 250

        Me.CtlCombats1.BringToFront()

        'set font
        SetFont()
    End Sub

    'Form overrides dispose to clean up the component list.
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
    Friend WithEvents btnLogon As System.Windows.Forms.Button
    Friend WithEvents btnNextPlayer As System.Windows.Forms.Button
    Friend WithEvents btnDeploy As System.Windows.Forms.Button
    Friend WithEvents btnMessages As System.Windows.Forms.Button
    Friend WithEvents btnResources As System.Windows.Forms.Button
    Friend WithEvents pnlMainClient As System.Windows.Forms.Panel
    Friend WithEvents txtTitleBox As System.Windows.Forms.TextBox
    Friend WithEvents pnlTopBorder As System.Windows.Forms.Panel
    Friend WithEvents picCampaignerIcon As System.Windows.Forms.PictureBox
    Friend WithEvents pnlMapClient As System.Windows.Forms.Panel

    Friend WithEvents btnExit As System.Windows.Forms.Button
    Friend WithEvents btnSave As System.Windows.Forms.Button
    Friend WithEvents btnOpen As System.Windows.Forms.Button
    Friend WithEvents btnModerator As System.Windows.Forms.Button
    Friend WithEvents pnlControlBox As System.Windows.Forms.Panel
    Friend WithEvents casAssets As CTest.ctlCampaignerAssets
    Friend WithEvents chiSelected As CTest.ctlSelectedChitProperties
    Friend WithEvents pnlLeftClient As System.Windows.Forms.Panel
    Friend WithEvents splHorizontal As System.Windows.Forms.Splitter
    Friend WithEvents pnlRightClient As System.Windows.Forms.Panel
    Friend WithEvents bttBattles As CTest.ctlBattleHandler
    Friend WithEvents btnChitManager As System.Windows.Forms.Button
    Friend WithEvents pnlLowerClient As System.Windows.Forms.Panel
    Friend WithEvents eveEventList As CTest.ctlEventLogViewer
    Friend WithEvents pnlLowerPanelTools As System.Windows.Forms.Panel
    Friend WithEvents pnlShowBattles As System.Windows.Forms.Panel
    Friend WithEvents pnlShowEventLog As System.Windows.Forms.Panel
    Friend WithEvents pnlShowMessageCenter As System.Windows.Forms.Panel
    Friend WithEvents mssCenter As CTest.ctlMessageCenter
    Friend WithEvents imlGeneralIcons As System.Windows.Forms.ImageList
    Friend WithEvents tmrReplay As System.Windows.Forms.Timer
    Friend WithEvents CtlCombats1 As CTest.ctlCombats
    Friend WithEvents fmvMap2 As CTest.FlexMapViewCampaignBuilder
    Friend WithEvents eocCombatResolution As CTest.ctlEndOfCombatPhase
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Me.components = New System.ComponentModel.Container
        Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(frmCampaignRunner))
        Dim CCampaignerMapMaker1 As CTest.cCampaignerMapMaker = New CTest.cCampaignerMapMaker
        Me.btnOpen = New System.Windows.Forms.Button
        Me.btnLogon = New System.Windows.Forms.Button
        Me.btnNextPlayer = New System.Windows.Forms.Button
        Me.btnDeploy = New System.Windows.Forms.Button
        Me.btnMessages = New System.Windows.Forms.Button
        Me.btnResources = New System.Windows.Forms.Button
        Me.pnlMainClient = New System.Windows.Forms.Panel
        Me.CtlCombats1 = New CTest.ctlCombats
        Me.pnlLeftClient = New System.Windows.Forms.Panel
        Me.chiSelected = New CTest.ctlSelectedChitProperties
        Me.splHorizontal = New System.Windows.Forms.Splitter
        Me.casAssets = New CTest.ctlCampaignerAssets
        Me.pnlRightClient = New System.Windows.Forms.Panel
        Me.fmvMap = New CTest.ctlCampaignerMapControl
        Me.pnlLowerClient = New System.Windows.Forms.Panel
        Me.pnlLowerPanelTools = New System.Windows.Forms.Panel
        Me.pnlShowMessageCenter = New System.Windows.Forms.Panel
        Me.pnlShowBattles = New System.Windows.Forms.Panel
        Me.pnlShowEventLog = New System.Windows.Forms.Panel
        Me.eveEventList = New CTest.ctlEventLogViewer
        Me.mssCenter = New CTest.ctlMessageCenter
        Me.bttBattles = New CTest.ctlBattleHandler
        Me.pnlMapClient = New System.Windows.Forms.Panel
        Me.fmvMap2 = New CTest.FlexMapViewCampaignBuilder
        Me.imlGeneralIcons = New System.Windows.Forms.ImageList(Me.components)
        Me.txtTitleBox = New System.Windows.Forms.TextBox
        Me.pnlTopBorder = New System.Windows.Forms.Panel
        Me.pnlControlBox = New System.Windows.Forms.Panel
        Me.picCampaignerIcon = New System.Windows.Forms.PictureBox
        Me.btnExit = New System.Windows.Forms.Button
        Me.btnSave = New System.Windows.Forms.Button
        Me.btnModerator = New System.Windows.Forms.Button
        Me.btnChitManager = New System.Windows.Forms.Button
        Me.tmrReplay = New System.Windows.Forms.Timer(Me.components)
        Me.eocCombatResolution = New CTest.ctlEndOfCombatPhase
        Me.btnVictory = New System.Windows.Forms.Button
        Me.pnlMainClient.SuspendLayout()
        Me.pnlLeftClient.SuspendLayout()
        Me.pnlRightClient.SuspendLayout()
        Me.pnlLowerClient.SuspendLayout()
        Me.pnlLowerPanelTools.SuspendLayout()
        Me.pnlMapClient.SuspendLayout()
        Me.pnlTopBorder.SuspendLayout()
        CType(Me.picCampaignerIcon, System.ComponentModel.ISupportInitialize).BeginInit()
        Me.SuspendLayout()
        '
        'btnOpen
        '
        Me.btnOpen.BackColor = System.Drawing.Color.LightSkyBlue
        Me.btnOpen.FlatStyle = System.Windows.Forms.FlatStyle.Flat
        Me.btnOpen.ForeColor = System.Drawing.Color.Black
        Me.btnOpen.Location = New System.Drawing.Point(49, 45)
        Me.btnOpen.Name = "btnOpen"
        Me.btnOpen.Size = New System.Drawing.Size(47, 23)
        Me.btnOpen.TabIndex = 0
        Me.btnOpen.Text = "Open"
        Me.btnOpen.UseVisualStyleBackColor = False
        '
        'btnLogon
        '
        Me.btnLogon.BackColor = System.Drawing.Color.DarkGray
        Me.btnLogon.Enabled = False
        Me.btnLogon.FlatStyle = System.Windows.Forms.FlatStyle.Flat
        Me.btnLogon.ForeColor = System.Drawing.Color.DimGray
        Me.btnLogon.Location = New System.Drawing.Point(149, 45)
        Me.btnLogon.Name = "btnLogon"
        Me.btnLogon.Size = New System.Drawing.Size(75, 23)
        Me.btnLogon.TabIndex = 1
        Me.btnLogon.Text = "Logon"
        Me.btnLogon.UseVisualStyleBackColor = False
        '
        'btnNextPlayer
        '
        Me.btnNextPlayer.BackColor = System.Drawing.Color.DarkGray
        Me.btnNextPlayer.Enabled = False
        Me.btnNextPlayer.FlatStyle = System.Windows.Forms.FlatStyle.Flat
        Me.btnNextPlayer.ForeColor = System.Drawing.Color.DimGray
        Me.btnNextPlayer.Location = New System.Drawing.Point(309, 45)
        Me.btnNextPlayer.Name = "btnNextPlayer"
        Me.btnNextPlayer.Size = New System.Drawing.Size(75, 23)
        Me.btnNextPlayer.TabIndex = 2
        Me.btnNextPlayer.Text = "Next Player"
        Me.btnNextPlayer.UseVisualStyleBackColor = False
        '
        'btnDeploy
        '
        Me.btnDeploy.BackColor = System.Drawing.Color.DarkGray
        Me.btnDeploy.Enabled = False
        Me.btnDeploy.FlatStyle = System.Windows.Forms.FlatStyle.Flat
        Me.btnDeploy.ForeColor = System.Drawing.Color.DimGray
        Me.btnDeploy.Location = New System.Drawing.Point(389, 45)
        Me.btnDeploy.Name = "btnDeploy"
        Me.btnDeploy.Size = New System.Drawing.Size(75, 23)
        Me.btnDeploy.TabIndex = 3
        Me.btnDeploy.Text = "Deploy"
        Me.btnDeploy.UseVisualStyleBackColor = False
        '
        'btnMessages
        '
        Me.btnMessages.BackColor = System.Drawing.Color.DarkGray
        Me.btnMessages.Enabled = False
        Me.btnMessages.FlatStyle = System.Windows.Forms.FlatStyle.Flat
        Me.btnMessages.ForeColor = System.Drawing.Color.DimGray
        Me.btnMessages.Location = New System.Drawing.Point(469, 45)
        Me.btnMessages.Name = "btnMessages"
        Me.btnMessages.Size = New System.Drawing.Size(75, 23)
        Me.btnMessages.TabIndex = 4
        Me.btnMessages.Text = "Messages"
        Me.btnMessages.UseVisualStyleBackColor = False
        '
        'btnResources
        '
        Me.btnResources.BackColor = System.Drawing.Color.DarkGray
        Me.btnResources.Enabled = False
        Me.btnResources.FlatStyle = System.Windows.Forms.FlatStyle.Flat
        Me.btnResources.ForeColor = System.Drawing.Color.DimGray
        Me.btnResources.Location = New System.Drawing.Point(632, 45)
        Me.btnResources.Name = "btnResources"
        Me.btnResources.Size = New System.Drawing.Size(75, 23)
        Me.btnResources.TabIndex = 5
        Me.btnResources.Text = "Resources"
        Me.btnResources.UseVisualStyleBackColor = False
        '
        'pnlMainClient
        '
        Me.pnlMainClient.Anchor = CType((((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom) _
                    Or System.Windows.Forms.AnchorStyles.Left) _
                    Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
        Me.pnlMainClient.BackColor = System.Drawing.Color.LightSteelBlue
        Me.pnlMainClient.Controls.Add(Me.CtlCombats1)
        Me.pnlMainClient.Controls.Add(Me.pnlLeftClient)
        Me.pnlMainClient.Controls.Add(Me.pnlRightClient)
        Me.pnlMainClient.Location = New System.Drawing.Point(8, 72)
        Me.pnlMainClient.Name = "pnlMainClient"
        Me.pnlMainClient.Size = New System.Drawing.Size(832, 576)
        Me.pnlMainClient.TabIndex = 7
        '
        'CtlCombats1
        '
        Me.CtlCombats1.Anchor = CType(((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom) _
                    Or System.Windows.Forms.AnchorStyles.Left), System.Windows.Forms.AnchorStyles)
        Me.CtlCombats1.BackgroundImage = CType(resources.GetObject("CtlCombats1.BackgroundImage"), System.Drawing.Image)
        Me.CtlCombats1.FMVMap = Nothing
        Me.CtlCombats1.Game = Nothing
        Me.CtlCombats1.Location = New System.Drawing.Point(8, 8)
        Me.CtlCombats1.MapBMP = Nothing
        Me.CtlCombats1.Name = "CtlCombats1"
        Me.CtlCombats1.Size = New System.Drawing.Size(209, 560)
        Me.CtlCombats1.TabIndex = 5
        Me.CtlCombats1.Visible = False
        '
        'pnlLeftClient
        '
        Me.pnlLeftClient.Anchor = CType(((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom) _
                    Or System.Windows.Forms.AnchorStyles.Left), System.Windows.Forms.AnchorStyles)
        Me.pnlLeftClient.Controls.Add(Me.chiSelected)
        Me.pnlLeftClient.Controls.Add(Me.splHorizontal)
        Me.pnlLeftClient.Controls.Add(Me.casAssets)
        Me.pnlLeftClient.Location = New System.Drawing.Point(8, 8)
        Me.pnlLeftClient.Name = "pnlLeftClient"
        Me.pnlLeftClient.Size = New System.Drawing.Size(210, 560)
        Me.pnlLeftClient.TabIndex = 3
        '
        'chiSelected
        '
        Me.chiSelected.BackColor = System.Drawing.Color.LightSkyBlue
        Me.chiSelected.Dock = System.Windows.Forms.DockStyle.Fill
        Me.chiSelected.GameData = Nothing
        Me.chiSelected.Location = New System.Drawing.Point(0, 222)
        Me.chiSelected.Name = "chiSelected"
        Me.chiSelected.PixelsPerOneMile = 0.0!
        Me.chiSelected.Size = New System.Drawing.Size(210, 338)
        Me.chiSelected.TabIndex = 4
        '
        'splHorizontal
        '
        Me.splHorizontal.BackColor = System.Drawing.Color.DarkSeaGreen
        Me.splHorizontal.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle
        Me.splHorizontal.Dock = System.Windows.Forms.DockStyle.Top
        Me.splHorizontal.Location = New System.Drawing.Point(0, 216)
        Me.splHorizontal.Name = "splHorizontal"
        Me.splHorizontal.Size = New System.Drawing.Size(210, 6)
        Me.splHorizontal.TabIndex = 3
        Me.splHorizontal.TabStop = False
        '
        'casAssets
        '
        Me.casAssets.CurrentGame = Nothing
        Me.casAssets.Dock = System.Windows.Forms.DockStyle.Top
        Me.casAssets.Location = New System.Drawing.Point(0, 0)
        Me.casAssets.MainButtonsEnabled = False
        Me.casAssets.Name = "casAssets"
        Me.casAssets.Size = New System.Drawing.Size(210, 216)
        Me.casAssets.TabIndex = 2
        '
        'pnlRightClient
        '
        Me.pnlRightClient.Anchor = CType((((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom) _
                    Or System.Windows.Forms.AnchorStyles.Left) _
                    Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
        Me.pnlRightClient.Controls.Add(Me.fmvMap)
        Me.pnlRightClient.Controls.Add(Me.pnlLowerClient)
        Me.pnlRightClient.Location = New System.Drawing.Point(224, 8)
        Me.pnlRightClient.Name = "pnlRightClient"
        Me.pnlRightClient.Size = New System.Drawing.Size(600, 560)
        Me.pnlRightClient.TabIndex = 4
        '
        'fmvMap
        '
        Me.fmvMap.Anchor = CType((((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom) _
                    Or System.Windows.Forms.AnchorStyles.Left) _
                    Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
        Me.fmvMap.BackColor = System.Drawing.Color.SteelBlue
        CCampaignerMapMaker1.CampaignerImages = CType(resources.GetObject("CCampaignerMapMaker1.CampaignerImages"), CTest.CampaignerImageLibrary)
        CCampaignerMapMaker1.FMPData = CType(resources.GetObject("CCampaignerMapMaker1.FMPData"), FMPLib01.FlexMapData)
        CCampaignerMapMaker1.LabelColor = System.Drawing.Color.Yellow
        CCampaignerMapMaker1.LabelSize = CType(16, Short)
        CCampaignerMapMaker1.MapOpened = False
        CCampaignerMapMaker1.SelectedChit = Nothing
        CCampaignerMapMaker1.ShowAllChits = True
        CCampaignerMapMaker1.showBattles = CTest.DisplayType_dt.Normal
        CCampaignerMapMaker1.ShowBorders = False
        CCampaignerMapMaker1.showDeploymentZones = CTest.DisplayType_dt.Normal
        CCampaignerMapMaker1.ShowGrid = CTest.DisplayType_dt.NotShown
        CCampaignerMapMaker1.ShowLabels = True
        CCampaignerMapMaker1.showLOS = CTest.DisplayType_dt.Normal
        CCampaignerMapMaker1.ShowMapOnly = True
        CCampaignerMapMaker1.showObjectives = CTest.DisplayType_dt.Normal
        CCampaignerMapMaker1.showReinforcementRange = CTest.DisplayType_dt.Normal
        CCampaignerMapMaker1.showWaypoints = CTest.DisplayType_dt.Normal
        CCampaignerMapMaker1.showZOC = CTest.DisplayType_dt.Normal
        Me.fmvMap.cmapper = CCampaignerMapMaker1
        Me.fmvMap.Deployment = False
        Me.fmvMap.FlexMap = CType(resources.GetObject("fmvMap.FlexMap"), FMPLib01.FlexMapData)
        Me.fmvMap.Location = New System.Drawing.Point(0, 1)
        Me.fmvMap.Name = "fmvMap"
        Me.fmvMap.SelectedChit = Nothing
        Me.fmvMap.ShowMapOnly = True
        Me.fmvMap.Size = New System.Drawing.Size(600, 417)
        Me.fmvMap.TabIndex = 4
        '
        'pnlLowerClient
        '
        Me.pnlLowerClient.BackColor = System.Drawing.Color.LightSkyBlue
        Me.pnlLowerClient.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle
        Me.pnlLowerClient.Controls.Add(Me.pnlLowerPanelTools)
        Me.pnlLowerClient.Controls.Add(Me.eveEventList)
        Me.pnlLowerClient.Controls.Add(Me.mssCenter)
        Me.pnlLowerClient.Controls.Add(Me.bttBattles)
        Me.pnlLowerClient.Dock = System.Windows.Forms.DockStyle.Bottom
        Me.pnlLowerClient.Location = New System.Drawing.Point(0, 424)
        Me.pnlLowerClient.Name = "pnlLowerClient"
        Me.pnlLowerClient.Size = New System.Drawing.Size(600, 136)
        Me.pnlLowerClient.TabIndex = 3
        '
        'pnlLowerPanelTools
        '
        Me.pnlLowerPanelTools.Anchor = CType((System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Left), System.Windows.Forms.AnchorStyles)
        Me.pnlLowerPanelTools.BackColor = System.Drawing.Color.DarkBlue
        Me.pnlLowerPanelTools.Controls.Add(Me.pnlShowMessageCenter)
        Me.pnlLowerPanelTools.Controls.Add(Me.pnlShowBattles)
        Me.pnlLowerPanelTools.Controls.Add(Me.pnlShowEventLog)
        Me.pnlLowerPanelTools.Location = New System.Drawing.Point(-1, -1)
        Me.pnlLowerPanelTools.Name = "pnlLowerPanelTools"
        Me.pnlLowerPanelTools.Size = New System.Drawing.Size(33, 137)
        Me.pnlLowerPanelTools.TabIndex = 11
        '
        'pnlShowMessageCenter
        '
        Me.pnlShowMessageCenter.BackgroundImage = CType(resources.GetObject("pnlShowMessageCenter.BackgroundImage"), System.Drawing.Image)
        Me.pnlShowMessageCenter.Location = New System.Drawing.Point(8, 64)
        Me.pnlShowMessageCenter.Name = "pnlShowMessageCenter"
        Me.pnlShowMessageCenter.Size = New System.Drawing.Size(16, 16)
        Me.pnlShowMessageCenter.TabIndex = 2
        '
        'pnlShowBattles
        '
        Me.pnlShowBattles.BackgroundImage = CType(resources.GetObject("pnlShowBattles.BackgroundImage"), System.Drawing.Image)
        Me.pnlShowBattles.Location = New System.Drawing.Point(8, 40)
        Me.pnlShowBattles.Name = "pnlShowBattles"
        Me.pnlShowBattles.Size = New System.Drawing.Size(16, 16)
        Me.pnlShowBattles.TabIndex = 0
        '
        'pnlShowEventLog
        '
        Me.pnlShowEventLog.BackgroundImage = CType(resources.GetObject("pnlShowEventLog.BackgroundImage"), System.Drawing.Image)
        Me.pnlShowEventLog.Location = New System.Drawing.Point(8, 16)
        Me.pnlShowEventLog.Name = "pnlShowEventLog"
        Me.pnlShowEventLog.Size = New System.Drawing.Size(16, 16)
        Me.pnlShowEventLog.TabIndex = 1
        '
        'eveEventList
        '
        Me.eveEventList.Anchor = CType(((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) _
                    Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
        Me.eveEventList.BackColor = System.Drawing.Color.LightSkyBlue
        Me.eveEventList.Enabled = False
        Me.eveEventList.Location = New System.Drawing.Point(32, -1)
        Me.eveEventList.Name = "eveEventList"
        Me.eveEventList.Size = New System.Drawing.Size(568, 137)
        Me.eveEventList.TabIndex = 3
        '
        'mssCenter
        '
        Me.mssCenter.Anchor = CType((((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom) _
                    Or System.Windows.Forms.AnchorStyles.Left) _
                    Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
        Me.mssCenter.BackColor = System.Drawing.Color.LightSkyBlue
        Me.mssCenter.Enabled = False
        Me.mssCenter.Location = New System.Drawing.Point(32, 0)
        Me.mssCenter.Name = "mssCenter"
        Me.mssCenter.Size = New System.Drawing.Size(567, 128)
        Me.mssCenter.TabIndex = 12
        '
        'bttBattles
        '
        Me.bttBattles.Anchor = CType(((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) _
                    Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
        Me.bttBattles.BackColor = System.Drawing.Color.LightSkyBlue
        Me.bttBattles.Location = New System.Drawing.Point(32, -1)
        Me.bttBattles.Name = "bttBattles"
        Me.bttBattles.Size = New System.Drawing.Size(568, 137)
        Me.bttBattles.TabIndex = 2
        '
        'pnlMapClient
        '
        Me.pnlMapClient.BackColor = System.Drawing.Color.LightSkyBlue
        Me.pnlMapClient.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle
        Me.pnlMapClient.Controls.Add(Me.fmvMap2)
        Me.pnlMapClient.Location = New System.Drawing.Point(204, 72)
        Me.pnlMapClient.Name = "pnlMapClient"
        Me.pnlMapClient.Size = New System.Drawing.Size(20, 19)
        Me.pnlMapClient.TabIndex = 1
        Me.pnlMapClient.Visible = False
        '
        'fmvMap2
        '
        Me.fmvMap2.Anchor = CType((((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom) _
                    Or System.Windows.Forms.AnchorStyles.Left) _
                    Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
        Me.fmvMap2.BattleIcon = CTest.FlexMapViewCampaignBuilder.BattleIconSize.Normal
        Me.fmvMap2.BridgeSelected = False
        Me.fmvMap2.CurrentGameData = Nothing
        Me.fmvMap2.FeaturePathOutlineColor = System.Drawing.Color.Yellow
        Me.fmvMap2.FMPData = CType(resources.GetObject("fmvMap2.FMPData"), FMPLib01.FlexMapData)
        Me.fmvMap2.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.75!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.fmvMap2.IconSize = CType(24, Short)
        Me.fmvMap2.LabelColor = System.Drawing.Color.Yellow
        Me.fmvMap2.LabelSize = CType(16, Short)
        Me.fmvMap2.Location = New System.Drawing.Point(3, 7)
        Me.fmvMap2.MapOpened = False
        Me.fmvMap2.Name = "fmvMap2"
        Me.fmvMap2.replayEnd = CType(0, Long)
        Me.fmvMap2.ReplayMode = False
        Me.fmvMap2.replayStart = CType(0, Long)
        Me.fmvMap2.SelectedBridge = Nothing
        Me.fmvMap2.SelectedChit = Nothing
        Me.fmvMap2.SelectedDeploymentZone = Nothing
        Me.fmvMap2.ShowAllObjectiveRuleRanges = False
        Me.fmvMap2.ShowBoundaries = True
        Me.fmvMap2.ShowDeploymentZones = True
        Me.fmvMap2.showGrid = False
        Me.fmvMap2.ShowLabels = True
        Me.fmvMap2.ShowLOS = Microsoft.VisualBasic.TriState.[True]
        Me.fmvMap2.ShowMapOnly = True
        Me.fmvMap2.ShowObjectives = Microsoft.VisualBasic.TriState.[True]
        Me.fmvMap2.ShowPaths = False
        Me.fmvMap2.showScale = False
        Me.fmvMap2.ShowScaleAndGrid = Microsoft.VisualBasic.TriState.[False]
        Me.fmvMap2.ShowSelectedObjectiveRuleRanges = False
        Me.fmvMap2.ShowWaypoints = Microsoft.VisualBasic.TriState.[True]
        Me.fmvMap2.ShowZOC = Microsoft.VisualBasic.TriState.[True]
        Me.fmvMap2.Size = New System.Drawing.Size(0, 0)
        Me.fmvMap2.TabIndex = 11
        Me.fmvMap2.VertexColor = System.Drawing.Color.AntiqueWhite
        Me.fmvMap2.VertexSize = CType(3, Short)
        Me.fmvMap2.ZoomFactor = 1.0!
        '
        'imlGeneralIcons
        '
        Me.imlGeneralIcons.ColorDepth = System.Windows.Forms.ColorDepth.Depth8Bit
        Me.imlGeneralIcons.ImageSize = New System.Drawing.Size(16, 16)
        Me.imlGeneralIcons.TransparentColor = System.Drawing.Color.Transparent
        '
        'txtTitleBox
        '
        Me.txtTitleBox.Anchor = CType(((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) _
                    Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
        Me.txtTitleBox.BackColor = System.Drawing.Color.SteelBlue
        Me.txtTitleBox.BorderStyle = System.Windows.Forms.BorderStyle.None
        Me.txtTitleBox.Font = New System.Drawing.Font("Microsoft Sans Serif", 15.75!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.txtTitleBox.ForeColor = System.Drawing.Color.WhiteSmoke
        Me.txtTitleBox.Location = New System.Drawing.Point(32, 8)
        Me.txtTitleBox.Multiline = True
        Me.txtTitleBox.Name = "txtTitleBox"
        Me.txtTitleBox.ReadOnly = True
        Me.txtTitleBox.Size = New System.Drawing.Size(728, 26)
        Me.txtTitleBox.TabIndex = 8
        Me.txtTitleBox.Text = "Campaigner [No Game Loaded]"
        '
        'pnlTopBorder
        '
        Me.pnlTopBorder.Anchor = CType(((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) _
                    Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
        Me.pnlTopBorder.BackColor = System.Drawing.Color.SteelBlue
        Me.pnlTopBorder.Controls.Add(Me.pnlControlBox)
        Me.pnlTopBorder.Controls.Add(Me.picCampaignerIcon)
        Me.pnlTopBorder.Controls.Add(Me.txtTitleBox)
        Me.pnlTopBorder.Location = New System.Drawing.Point(0, 0)
        Me.pnlTopBorder.Name = "pnlTopBorder"
        Me.pnlTopBorder.Size = New System.Drawing.Size(856, 40)
        Me.pnlTopBorder.TabIndex = 8
        '
        'pnlControlBox
        '
        Me.pnlControlBox.Anchor = CType((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
        Me.pnlControlBox.BackColor = System.Drawing.Color.DarkBlue
        Me.pnlControlBox.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle
        Me.pnlControlBox.Location = New System.Drawing.Point(768, 8)
        Me.pnlControlBox.Name = "pnlControlBox"
        Me.pnlControlBox.Size = New System.Drawing.Size(72, 24)
        Me.pnlControlBox.TabIndex = 10
        '
        'picCampaignerIcon
        '
        Me.picCampaignerIcon.Location = New System.Drawing.Point(9, 11)
        Me.picCampaignerIcon.Name = "picCampaignerIcon"
        Me.picCampaignerIcon.Size = New System.Drawing.Size(16, 16)
        Me.picCampaignerIcon.TabIndex = 9
        Me.picCampaignerIcon.TabStop = False
        '
        'btnExit
        '
        Me.btnExit.BackColor = System.Drawing.Color.LightSkyBlue
        Me.btnExit.FlatStyle = System.Windows.Forms.FlatStyle.Flat
        Me.btnExit.ForeColor = System.Drawing.Color.Black
        Me.btnExit.Location = New System.Drawing.Point(8, 45)
        Me.btnExit.Name = "btnExit"
        Me.btnExit.Size = New System.Drawing.Size(42, 23)
        Me.btnExit.TabIndex = 11
        Me.btnExit.Text = "Exit"
        Me.btnExit.UseVisualStyleBackColor = False
        '
        'btnSave
        '
        Me.btnSave.BackColor = System.Drawing.Color.LightSkyBlue
        Me.btnSave.FlatStyle = System.Windows.Forms.FlatStyle.Flat
        Me.btnSave.ForeColor = System.Drawing.Color.Black
        Me.btnSave.Location = New System.Drawing.Point(95, 45)
        Me.btnSave.Name = "btnSave"
        Me.btnSave.Size = New System.Drawing.Size(42, 23)
        Me.btnSave.TabIndex = 12
        Me.btnSave.Text = "Save"
        Me.btnSave.TextAlign = System.Drawing.ContentAlignment.MiddleLeft
        Me.btnSave.UseVisualStyleBackColor = False
        '
        'btnModerator
        '
        Me.btnModerator.BackColor = System.Drawing.Color.DarkGray
        Me.btnModerator.Enabled = False
        Me.btnModerator.FlatStyle = System.Windows.Forms.FlatStyle.Flat
        Me.btnModerator.ForeColor = System.Drawing.Color.DimGray
        Me.btnModerator.Location = New System.Drawing.Point(229, 45)
        Me.btnModerator.Name = "btnModerator"
        Me.btnModerator.Size = New System.Drawing.Size(75, 23)
        Me.btnModerator.TabIndex = 13
        Me.btnModerator.Text = "Moderator"
        Me.btnModerator.UseVisualStyleBackColor = False
        '
        'btnChitManager
        '
        Me.btnChitManager.BackColor = System.Drawing.Color.DarkGray
        Me.btnChitManager.Enabled = False
        Me.btnChitManager.FlatStyle = System.Windows.Forms.FlatStyle.Flat
        Me.btnChitManager.ForeColor = System.Drawing.Color.DimGray
        Me.btnChitManager.Location = New System.Drawing.Point(552, 45)
        Me.btnChitManager.Name = "btnChitManager"
        Me.btnChitManager.Size = New System.Drawing.Size(75, 23)
        Me.btnChitManager.TabIndex = 14
        Me.btnChitManager.Text = "Manager"
        Me.btnChitManager.UseVisualStyleBackColor = False
        '
        'tmrReplay
        '
        Me.tmrReplay.Interval = 500
        '
        'eocCombatResolution
        '
        Me.eocCombatResolution.Anchor = CType((((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom) _
                    Or System.Windows.Forms.AnchorStyles.Left) _
                    Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
        Me.eocCombatResolution.BackColor = System.Drawing.Color.Black
        Me.eocCombatResolution.ForeColor = System.Drawing.Color.Black
        Me.eocCombatResolution.GameData = Nothing
        Me.eocCombatResolution.Location = New System.Drawing.Point(8, 72)
        Me.eocCombatResolution.MapBMP = Nothing
        Me.eocCombatResolution.MapData = Nothing
        Me.eocCombatResolution.Name = "eocCombatResolution"
        Me.eocCombatResolution.Size = New System.Drawing.Size(832, 576)
        Me.eocCombatResolution.TabIndex = 6
        Me.eocCombatResolution.Visible = False
        '
        'btnVictory
        '
        Me.btnVictory.BackColor = System.Drawing.Color.DarkGray
        Me.btnVictory.Enabled = False
        Me.btnVictory.FlatStyle = System.Windows.Forms.FlatStyle.Flat
        Me.btnVictory.ForeColor = System.Drawing.Color.DimGray
        Me.btnVictory.Location = New System.Drawing.Point(713, 45)
        Me.btnVictory.Name = "btnVictory"
        Me.btnVictory.Size = New System.Drawing.Size(75, 23)
        Me.btnVictory.TabIndex = 15
        Me.btnVictory.Text = "Victory"
        Me.btnVictory.UseVisualStyleBackColor = False
        '
        'frmCampaignRunner
        '
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
        Me.BackColor = System.Drawing.Color.Black
        Me.ClientSize = New System.Drawing.Size(848, 654)
        Me.Controls.Add(Me.btnVictory)
        Me.Controls.Add(Me.pnlMapClient)
        Me.Controls.Add(Me.eocCombatResolution)
        Me.Controls.Add(Me.btnChitManager)
        Me.Controls.Add(Me.btnModerator)
        Me.Controls.Add(Me.btnSave)
        Me.Controls.Add(Me.btnExit)
        Me.Controls.Add(Me.pnlTopBorder)
        Me.Controls.Add(Me.pnlMainClient)
        Me.Controls.Add(Me.btnResources)
        Me.Controls.Add(Me.btnMessages)
        Me.Controls.Add(Me.btnDeploy)
        Me.Controls.Add(Me.btnNextPlayer)
        Me.Controls.Add(Me.btnLogon)
        Me.Controls.Add(Me.btnOpen)
        Me.ForeColor = System.Drawing.Color.White
        Me.Icon = CType(resources.GetObject("$this.Icon"), System.Drawing.Icon)
        Me.Name = "frmCampaignRunner"
        Me.Text = "Campaigner"
        Me.pnlMainClient.ResumeLayout(False)
        Me.pnlLeftClient.ResumeLayout(False)
        Me.pnlRightClient.ResumeLayout(False)
        Me.pnlLowerClient.ResumeLayout(False)
        Me.pnlLowerPanelTools.ResumeLayout(False)
        Me.pnlMapClient.ResumeLayout(False)
        Me.pnlTopBorder.ResumeLayout(False)
        Me.pnlTopBorder.PerformLayout()
        CType(Me.picCampaignerIcon, System.ComponentModel.ISupportInitialize).EndInit()
        Me.ResumeLayout(False)

    End Sub

#End Region


#Region "Properties"

    Private Property DeployUnit() As Boolean
        Get
            Return m_DeployUnit
        End Get
        Set(ByVal Value As Boolean)
            m_DeployUnit = Value
            fmvMap.Deployment = Value

            If m_DeployUnit = True Then
                btnDeploy.BackColor = c_TOGGLEBUTTONACTIVECOLOR
            Else
                If btnDeploy.Enabled = False Then
                    btnDeploy.BackColor = c_DISABLEDBUTTONBACKCOLOR
                Else
                    btnDeploy.BackColor = c_TOGGLEBUTTONINACTIVECOLOR
                End If

            End If
        End Set
    End Property

    Private Property ToolBarEnablementLevel() As EnablementLevel
        Get
            Return m_ToolBarEnablementLevel
        End Get
        Set(ByVal Value As EnablementLevel)
            m_ToolBarEnablementLevel = Value
            Select Case m_ToolBarEnablementLevel
                Case EnablementLevel.NoneEnable
                    ' disable all but the file options
                    DisableButton(btnLogon)
                    DisableButton(btnDeploy)
                    DisableButton(btnMessages)
                    DisableButton(btnResources)
                    DeployUnit = False
                    DisableButton(btnDeploy)
                    DisableButton(btnModerator)
                    DisableButton(btnChitManager)
                    DisableButton(btnVictory)
                    btnNextPlayer.Text = "Next Player"
                Case EnablementLevel.GameLoaded
                    EnableButton(btnLogon)
                Case EnablementLevel.PlayerLoggedIn
                    EnableButton(btnNextPlayer)
                    EnableButton(btnDeploy)
                    DeployUnit = False
                    EnableButton(btnMessages)
                    EnableButton(btnResources)
                    EnableButton(btnVictory)

                    If CurrentGame.AllowPlayerManageChits Then
                        EnableButton(btnChitManager)
                    Else
                        DisableButton(btnChitManager)
                    End If
                    LogPlayerIn()
                    txtTitleBox.Text = GameTitle & " [" & CurrentGame.GameName & "-" & CurrentGame.selectedPlayer.PlayerName & "] (" & CurrentGame.ElapsedTime.ToString & ")"
                Case EnablementLevel.PlayerLoggedOut

                    DisableButton(btnResources)
                    DisableButton(btnMessages)
                    DeployUnit = False
                    DisableButton(btnDeploy)
                    DisableButton(btnModerator)
                    DisableButton(btnNextPlayer)
                    DisableButton(btnChitManager)
                    btnNextPlayer.Text = "Next Player"
                    LogPlayerOut()
                    txtTitleBox.Text = GameTitle & " [" & CurrentGame.GameName & "]"
                Case EnablementLevel.UnitSelected

                Case EnablementLevel.ModeratorLoggedIn
                    EnableButton(btnModerator)
                    EnableButton(btnNextPlayer)
                    EnableButton(btnChitManager)
                    DeployUnit = False
                    DisableButton(btnDeploy)
                    '// 4/18/2007
                    'LogModeratorIn()
                    btnNextPlayer.Text = "Log Off"
                    txtTitleBox.Text = GameTitle & " [" & CurrentGame.GameName & "-Moderator] (" & CurrentGame.Turn & ")"
                    eveEventList.ListEvents(CurrentGame)
            End Select
        End Set
    End Property

#End Region


    Private Sub SetFont()
        ' retrieves the font to use

    End Sub

    Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click
        Me.Dispose()
    End Sub

    Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
        SaveGame()
    End Sub

    Private Sub btnLogon_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLogon.Click
        DoLogon()
    End Sub

    Private Sub btnModerator_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnModerator.Click
        Dim frmMod As New frmModeratorActions(CurrentGame)
        frmMod.ShowDialog()

    End Sub

    Private Sub btnNextPlayer_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNextPlayer.Click
        NextPlayer()
        ToolBarEnablementLevel = EnablementLevel.PlayerLoggedOut
    End Sub

    Private Function OpenGame() As Boolean
        ' we must check to see if there are unresolved combats and such so we get into the right turnmode
        Dim frmOpenGame As OpenFileDialog
        Dim allPlayersCombatComplete As Boolean

        frmOpenGame = New OpenFileDialog
        frmOpenGame.Filter = "Campaigner Game Data | *.cgd"
        frmOpenGame.ShowDialog()

        ' clear the existing game and put in the new one
        CurrentGame = New CampaignerGameData

        Try
            CurrentGame = CurrentGame.Open(frmOpenGame.FileName)

            ' we need to recalculate averageunitpv and averageobjectivemaxpv, just to make sure its right on startup
            CurrentGame.AverageUnitMaxPV = CalculateAverageMaxPV(GroundChitClass_cgd.Unit)
            CurrentGame.AverageObjectiveMaxPV = CalculateAverageMaxPV(GroundChitClass_cgd.Objective)
            CurrentGame.MaxPointValueDeployed = CalculateMaxDeployedPV(GroundChitClass_cgd.Unit)

            ' set the map without objectives, or units
            ' find the map its always under the campaigns\maps directory really.
            Dim totalPath As String = System.AppDomain.CurrentDomain.BaseDirectory & "\campaigns\maps\"

            fmvMap.ShowMapOnly = True
            fmvMap.OpenFlexMapFromGame(CurrentGame)
            GameLoaded = True
            PopulateOrdersList()
            txtTitleBox.Text = "Campaigner [" & CurrentGame.GameName & "] (" & CurrentGame.Turn & ")"
            casAssets.CurrentGame = CurrentGame
            HandleGenericPropertiesForOpen()

            ' set the scale for this map for these units
            SetScaleForChits()

            ' TODO: Handle this better right here.
            If CheckForUnresolvedCombats(allPlayersCombatComplete) = True Then
                If allPlayersCombatComplete = True Then
                    eocCombatResolution.GameData = CurrentGame
                    eocCombatResolution.Visible = True
                End If
                mTurnMode = TurnMode.CombatTurn
            End If

            '// pixelsper mile for the selectedchit
            chiSelected.PixelsPerOneMile = fmvMap.PixelsPerOneMile

            '// update the bitmap and crud in the end of combat screen
            eocCombatResolution.MapData = fmvMap.FlexMap
            eocCombatResolution.MapBMP = fmvMap.MapBMP
            eocCombatResolution.GameData = CurrentGame

            '// the uhm...selected chit statistics
            chiSelected.GameData = CurrentGame
            chiSelected.PopulateStatisticBenchmarks()

            '// we now have to set the flexmap 
            'newTurnGrinder.FlexMap = fmvMap.FlexMap

            Return True
        Catch serEx As SerializationException
            MessageBox.Show("The file does not match versions. ", "Invalid Version", MessageBoxButtons.OK)
            Return False
        Catch ex As Exception
            HandleException(c_Module, ex)
            Return False
        End Try

    End Function

    Private Sub SetScaleForChits()
        ' set the units values for the map scale, by setting the number of pixels for drawing and such
        Dim pixelsPerOneMile As Integer = fmvMap.PixelsPerOneMile

        'Dim gc As GroundChitType
        'Dim gcKey As String

        Try
            For Each mem As ChitMember In CurrentGame.Chits
                'GC = CurrentGame.AllChits.Item(gcKey)
                'GC.EffectiveLOSRange = GC.LOS * pixelsPerOneMile
                'GC.EffectiveZOC = GC.ZOCRange * pixelsPerOneMile
            Next
        Catch ex As Exception
            HandleException("frmCampaignRunner.SetScaleForChits", ex)
        End Try

    End Sub

    Private Sub HandleGenericPropertiesForOpen()
        ' handles the generic properties when opening a file
        Dim gen As GenericProperty
        Try
            For Each gen In CurrentGame.ExtendedProperties
                Select Case gen.PropertyName
                    Case Is = "LabelType1"
                        AddTemporaryLabelToFMP(gen)
                End Select
            Next
        Catch ex As Exception
            HandleException("frmCampaignRunner.HandleGenericPropertiesForOpen", ex)
        End Try

    End Sub

    Private Sub AddTemporaryLabelToFMP(ByVal gen As GenericProperty)
        'Dim lab As New FMPLib01.FlexMapData.MapLabel
        '' use the labels function to populate its own properties. Cuz, that ro><0rz
        'Try
        '    lab.text = "boo"
        '    lab.FromString(gen.PropertyValue)

        '    'fmvMap2.FMPData.TemporaryLabels.Add(lab)
        'Catch ex As Exception
        '    HandleException("frmCampaignRunner.AddTemporaryLabelToFMP", ex)
        'End Try

    End Sub

    Private Sub SaveGame()
        Dim frmSaveGame As SaveFileDialog
        frmSaveGame = New SaveFileDialog
        frmSaveGame.Filter = "Campaigner Game Data | *.cgd"

        frmSaveGame.ShowDialog()

        Try
            CurrentGame.Save(frmSaveGame.FileName)
        Catch ex As Exception
            HandleException(c_Module, ex)
        End Try

    End Sub

    Private Sub LogPlayerIn()
        ' we make sure the current player is logged out
        Try
            casAssets.Refresh()
            casAssets.MainButtonsEnabled = True
            fmvMap.ShowMapOnly = False

            ' enable and populate
            bttBattles.Enabled = True
            eveEventList.Enabled = True
            mssCenter.Enabled = True

            eveEventList.Visible = False
            mssCenter.Visible = False

            bttBattles.ShowBattles(CurrentGame)
            eveEventList.ListEvents(CurrentGame)
            mssCenter.ShowMessages(CurrentGame)

            ' check for combat turn
            If mTurnMode = TurnMode.CombatTurn Then
                SetUpCombatPanel()
            Else
                ' if it is a combat turn, put the battles in the battles listing on the combats panel
                ClearCombatPanel()
            End If

            fmvMap.RedrawAndRender()

        Catch ex As Exception
            HandleException("frmCampaignRunner.LogPlayerIn", ex)
        End Try

    End Sub

    Private Sub LogModeratorIn()
        Try
            casAssets.Refresh()
            fmvMap.ShowMapOnly = False
            eveEventList.Enabled = True
            mssCenter.Enabled = True
            eveEventList.Visible = True
            mssCenter.Enabled = False
            eveEventList.ListEvents(CurrentGame)
            mssCenter.ShowMessages(CurrentGame)

            fmvMap.RedrawAndRender()

        Catch ex As Exception
            HandleException("frmCampaignRunner.LogModeratorIn", ex)
        End Try
    End Sub

    Private Sub SetUpCombatPanel()
        ' setup combat panel
        CtlCombats1.ClearData()

        CtlCombats1.Game = CurrentGame
        CtlCombats1.FMVMap = fmvMap.FlexMap
        CtlCombats1.Visible = True
        PaintDanger(pnlMainClient)

    End Sub

    Private Sub ClearCombatPanel()
        CtlCombats1.ClearData()
        CtlCombats1.Visible = False
        pnlMainClient.BackColor = Color.LightSteelBlue
    End Sub

    Private Sub LogPlayerOut()
        Try
            DeployUnit = False
            CurrentGame.selectedPlayer = Nothing

            ' handle the lower panel
            eveEventList.ClearList()
            mssCenter.ClearData()

            eveEventList.Visible = False
            mssCenter.Enabled = False
            bttBattles.Visible = True

            eveEventList.Enabled = False
            bttBattles.Enabled = False
            mssCenter.Enabled = False

            chiSelected.ClearSelectedList()

            casAssets.Refresh()
            casAssets.MainButtonsEnabled = False

            fmvMap.ClearSelectedChit()
            fmvMap.ShowMapOnly = True

            fmvMap.HaltReplay()
            fmvMap.RedrawAndRender()

            CtlCombats1.ClearData()

        Catch ex As Exception
            HandleException("frmCampaignRunner.LogPlayerOut", ex)
        End Try
    End Sub

    Private Sub NextPlayer()

        Try
            CurrentGame.selectedPlayer.TurnComplete = True
            CurrentGame.selectedPlayer = Nothing

            ' check each player to determine if everyone is done
            Dim play As Player
            Dim key As String
            Dim numComplete As Int16
            Dim totalPlayers As Int32
            Dim turnComplete As Boolean

            totalPlayers = CurrentGame.Players.Count - 1    ' minus one for the moderator

            turnComplete = AllPlayersCompleted()

            LogPlayerOut()

            ' the turn is done if all players are done.
            If turnComplete Then

                ' check if this is a combat turn or was a combat turn and needs to be processed.
                If mTurnMode = TurnMode.NormalTurn Then
                    GenerateTurn()
                    ' reset player complete
                    ResetPlayerComplete()
                    ' check to see if this should be turned into a combat turn.
                    If CurrentGame.Battles_g.HT.Count > 0 Then
                        mTurnMode = TurnMode.CombatTurn
                        ' if it is a combat turn, reset player status for players engaged in combat. Returns the number of players
                        ' that are NOT in combat
                        numComplete = ResetForCombatPlayers()
                        bttBattles.ClearBattles()
                        bttBattles.ShowBattles(CurrentGame)
                    End If
                Else
                    ' yeah. its a combat turn, lets do what we need to (the combat turn is over)
                    ' show the orders of battle
                    Dim fBattleList As New frmBattlesListing
                    fBattleList.ShowDialog(CurrentGame, fmvMap.FlexMap)
                    '// here is where we'll show the combat resolutions screen instead of a popup. This control will have a button
                    '// to apply the combatresults 
                    ShowCombatResolution()
                End If

            End If

        Catch ex As Exception
            HandleException("frmCampaignRunner.NextPlayer", ex)
        End Try

    End Sub

    Private Sub ShowCombatResolution()
        eocCombatResolution.MapData = fmvMap.FlexMap
        eocCombatResolution.GameData = CurrentGame
        eocCombatResolution.MapBMP = fmvMap.MapBMP

        CtlCombats1.Visible = False
        eocCombatResolution.Visible = True
    End Sub

    Private Function AllPlayersCompleted() As Boolean
        Dim key As String
        Dim play As Player

        For Each key In CurrentGame.Players.Keys
            play = CType(CurrentGame.Players.Item(key), Player)
            If Not play.PlayerName = "<Moderator>" Then
                '// if at least one player is not completed, then we wait.
                If play.TurnComplete = False Then Return False
            End If
        Next
        '// if nothing has returned false already, we must be okay.
        Return True

    End Function

    Private Function PlayerCompleteCount() As Integer
        ' returns the number of players that are finished with their turn
        Dim numComplete As Integer
        Dim key As String
        Dim play As Player

        For Each key In CurrentGame.Players.Keys
            play = CType(CurrentGame.Players.Item(key), Player)
            If play.PlayerName <> "Moderator" Then
                If play.TurnComplete = True Then
                    numComplete += 1
                End If
            End If
        Next

        Return numComplete

    End Function

    Private Sub ResetPlayerComplete()
        Dim key As String
        Dim play As Player

        For Each key In CurrentGame.Players.Keys
            play = CType(CurrentGame.Players.Item(key), Player)
            If play.PlayerName <> "Moderator" Then
                play.TurnComplete = False
            End If
        Next
    End Sub

    Private Sub GenerateTurn()
        Try
            MessageBox.Show("Generating New Turn...", "Info: New Turn", MessageBoxButtons.OK, MessageBoxIcon.Information)

            If CurrentGame.Turn = 0 Then
                CurrentGame.ResetRemainingTime()
                CurrentGame.Turn = 1
            End If

            newTurnGrinder = New CampaignerCombatEngine.CampaignerCombatEngineB
            'newTurnGrinder.FlexMap = fmvMap.FlexMap
            newTurnGrinder.GenerateCombatTurn(CurrentGame, c_COMBATPHASES)

            Dim pixelsPerOneMile As Integer = fmvMap.FlexMap.MapScale.PixelCount / fmvMap.FlexMap.MapScale.MilesPerPixelCount

            ' TODO: Reset Rule Maximums for Objectives and Tokens (should be done in the turn generator, eh?)
            ' Reset moveremaining and status and battle involved in for next turn, only if remainingTime is zero.
            If CurrentGame.remainingTime <= TimeSpan.Zero Then
                For Each mem As ChitMember In CurrentGame.Chits

                    If mem.UnitType = GroundChitClass_cgd.Battlegroup Then
                        ' determine how many pixels a unit can move per game turn.
                        DirectCast(mem, BattlegroupChit).moveRemaining = DirectCast(mem, BattlegroupChit).movementSpeed * pixelsPerOneMile
                        'unit.MoveRemaining = unit.MovementSpeed * pixelsPerOneMile
                    Else
                        DirectCast(mem, InstallationChit).GenerateResources()
                    End If

                    '// since anything can have rules...
                    mem.ResetRuleCount()
                Next
                '// reset the time remaining for the next turn.
                CurrentGame.ResetRemainingTime()
                CurrentGame.Turn += 1 '// this may no longer be needed...
            End If

            CurrentGame.AverageUnitMaxPV = CalculateAverageMaxPV(GroundChitClass_cgd.Unit)
            CurrentGame.AverageObjectiveMaxPV = CalculateAverageMaxPV(GroundChitClass_cgd.Objective)

            '// lets calculate the total deployed point value.
            CalculateCurrentDeployedPV()
            FulfillVictoryConditions()
            CheckForFinalVictory()

            '// update stats stuff.
            chiSelected.PopulateStatisticBenchmarks()

            'Dim k As String
            Dim s As String
            For Each s In CurrentGame.ReplayPhaseKeysCol
                '    s = CurrentGame.replayPhaseKeys.Item(k)
                Debug.WriteLine("Phase found: " & s)
            Next

        Catch ex As Exception
            HandleException("frmCampaignRunner.GenerateTurn", ex)
        End Try

    End Sub

    Private Sub FulfillVictoryConditions()
        Dim fact As Faction
        Dim factkey As String
        Dim vict As IVictoryCondition

        Try
            For Each factkey In CurrentGame.Faction_g.HT.Keys
                fact = CurrentGame.Faction_g.Item(factkey)
                For Each vict In fact.FactionVictoryConditions
                    Select Case vict.VCType
                        Case VictoryConditionClass_cgd.AreaObjective
                            If IsAOVictoryMet(vict, fact) Then
                                vict.Achieved = True
                            Else
                                vict.Achieved = False
                            End If
                        Case VictoryConditionClass_cgd.AttritionObjective
                            If IsAttritionVictoryMet(vict, fact) Then
                                vict.Achieved = True
                            Else
                                vict.Achieved = False
                            End If
                        Case VictoryConditionClass_cgd.ChitDestruction
                            If IsChitDestructionVictoryMet(vict) Then
                                vict.Achieved = True
                            Else
                                vict.Achieved = False
                            End If
                        Case VictoryConditionClass_cgd.Resource
                            If IsResourceVictoryMet(vict, fact) Then
                                vict.Achieved = True
                            Else
                                vict.Achieved = False
                            End If
                        Case Else
                            ' this would be finalvictory. We calculate that later.

                    End Select
                Next
            Next
        Catch ex As Exception
            HandleException("frmCampaignRunner.FulfillVictoryConditions", ex)
        End Try

    End Sub

    Private Function IsAOVictoryMet(ByRef AOVict As AreaObjectiveVictoryCondition, ByRef forFact As Faction) As Boolean

        Try
            If AOVict.TargetAreaObjective.OwningFaction = forFact.FactionID Then
                If Not AOVict.TargetAreaObjective.IsContested Then
                    Return True
                Else
                    Return False
                End If

            Else
                Return False
            End If
        Catch ex As Exception
            HandleException("frmCampaignRunner.IsAOVictoryMet", ex)
        End Try

    End Function

    Private Function IsAttritionVictoryMet(ByRef ATVict As AttritionVictoryCondition, ByVal forFact As Faction) As Boolean
        Dim factKey As String
        Dim otherFact As Faction

        Try
            For Each factKey In CurrentGame.Faction_g.HT.Keys
                otherFact = CurrentGame.Faction_g.Item(factKey)
                If otherFact.FactionID <> forFact.FactionID Then
                    Exit For
                End If
            Next

            Dim depPoints As Long
            Dim totalDep As Long
            Dim maxPoints As Long
            Dim freePoints As Long  '// points not deployed
            Dim NumberRequirements As Byte
            Dim numberRequirementsMet As Byte

            depPoints = otherFact.FactionDeployedPoints
            totalDep = otherFact.FactionTotalDeployedPoints
            maxPoints = otherFact.FactionTotalPoints
            freePoints = otherFact.FactionFreePoints

            If ATVict.DeployedReductionPercent <> -1 Then
                NumberRequirements += 1
                Try
                    Dim per As Single = (depPoints / totalDep) * 100
                    If per <= ATVict.DeployedReductionPercent Then
                        numberRequirementsMet += 1
                    End If
                Catch ex As Exception
                    HandleException(c_Module, ex)
                End Try
            End If

            If ATVict.TotalPointValueReductionPercent <> -1 Then
                NumberRequirements += 1
                Try
                    Dim per As Single = (depPoints / (maxPoints - freePoints)) * 100
                    If per <= ATVict.TotalPointValueReductionPercent Then
                        numberRequirementsMet += 1
                    End If
                Catch ex As Exception
                    HandleException(c_Module, ex)
                End Try
            End If

            If numberRequirementsMet = NumberRequirements Then
                Return True
            Else
                Return False
            End If

        Catch ex As Exception
            HandleException("frmCampaignRunner.IsAttritionVictoryMet", ex)
        End Try

    End Function

    Private Function IsChitDestructionVictoryMet(ByRef CDVictory As ChitDestructionVictoryCondition) As Boolean
        Try
            If CDVictory.ChitToDestroy.Status = GroundUnitStatus_cgd.Dead Then Return True
        Catch nullEx As NullReferenceException
            Return True ' its gone man!
        Catch ex As Exception
            HandleException(c_Module, ex)
        End Try

        ' if its not dead and it exists, the victory condition is NOT met.
        Return False

    End Function

    Private Function IsResourceVictoryMet(ByRef RSVict As ResourceVictoryCondition, ByRef forFact As Faction) As Boolean
        'Dim targetResource As ResourceType

        Dim currentResAmount As Long
        Try
            Dim cm As ChitMember
            Dim inst As InstallationChit

            For Each cm In CurrentGame.Chits
                If TypeOf cm Is InstallationChit Then
                    inst = cm
                    For Each resitem As ResourcePoolItem In inst.Resources
                        If resitem.resourceTypeptr.Equals(RSVict.TargetResourceType) Then
                            currentResAmount += resitem.localAmount
                            If currentResAmount >= RSVict.AmountNeeded Then
                                Return True
                            End If
                        End If
                    Next
                End If
            Next

        Catch ex As Exception
            HandleException(c_Module, ex)
        End Try

        ' if we don't short-circuit, we don't have enough.
        Return False

    End Function

    Private Sub CheckForFinalVictory()
        ' all we currently do is post a messagebox saying... "hey, joe won"
        ' later, a window will show or something. I dunno.

        Dim fact As Faction

        Dim victRes As String 'YY or NN or YN or NY
        Dim factKey As String
        Dim totalAchievedVP As Integer
        Dim requiredVP As Integer
        Dim vict As IVictoryCondition

        Try
            For Each factKey In CurrentGame.Faction_g.HT.Keys
                fact = CurrentGame.Faction_g.Item(factKey)
                totalAchievedVP = 0
                Dim factFinal As FinalVictoryCondition

                '// check for no victory conditions
                If Not fact.FactionVictoryConditions Is Nothing Then
                    If fact.FactionVictoryConditions.Count > 0 Then
                        For Each vict In fact.FactionVictoryConditions
                            If vict.Achieved = True Then
                                totalAchievedVP += vict.VPValue
                            End If
                            If TypeOf vict Is FinalVictoryCondition Then
                                factFinal = vict
                            End If
                        Next
                        If factFinal.VPValue > 0 Then
                            If totalAchievedVP >= factFinal.VPValue Then
                                MessageBox.Show(fact.FactionName & " has achieved its target of victory conditions.", "Victory")
                            End If
                        End If
                    End If
                End If

            Next

        Catch ex As Exception
            HandleException(c_Module, ex)
        End Try
    End Sub

    Private Function ResetForCombatPlayers() As Integer
        Dim playKey As String
        Dim play As Player
        Dim numNotInCombat As Integer

        Try
            For Each playKey In CurrentGame.Players.Keys
                play = CurrentGame.Players.Item(playKey)
                If play.PlayerName <> "<Moderator>" Then
                    If play.IsInCombat Then
                        ' only show players currently in combat.
                        play.TurnComplete = False
                    Else
                        play.TurnComplete = True
                        numNotInCombat += 1
                    End If
                End If
            Next
            ' return the number of players not in combat 
            Return numNotInCombat
        Catch ex As Exception
            HandleException("frmCampaignRunner.ResetForCombatPlayers", ex)
        End Try

    End Function

    Private Sub ApplyCombatResults()
        Dim TurnGrinder As New CampaignerCombatEngine.CampaignerCombatEngineB
        'TurnGrinder.FlexMap = fmvMap2.FMPData

        Try
            TurnGrinder.ApplyCombatResults(CurrentGame)
            mTurnMode = TurnMode.NormalTurn
        Catch ex As Exception
            HandleException("frmCampaignRunner.ApplyCombatResults", ex)
        End Try

    End Sub

    Private Sub btnOpen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOpen.Click
        If OpenGame() = True Then ToolBarEnablementLevel = EnablementLevel.GameLoaded
    End Sub

    Private Sub PopulateOrdersList()
        Dim key As String
        Dim ord As OrderType
        Try
            For Each key In CurrentGame.Orders_g.HT.Keys
                ord = CurrentGame.Orders_g.Item(key)
            Next
        Catch ex As Exception
            HandleException("frmCampaignRunner.PopulateOrdersList", ex)
        End Try

    End Sub

    Private Sub DoLogon()
        If CurrentGame.Players.Count = 0 Then
            MessageBox.Show("There are no players in this game. The moderator must create players first.", "No Players", MessageBoxButtons.OK)
            Exit Sub
        End If

        ' if there are unresolved combats, only show players that are in combat, and the logon form is smart enough 
        ' to deal with it.

        '// make sure no one is still logged in
        LogPlayerOut()

        Dim frmLogon As New frmCampaignerPasswordDialog(CurrentGame)
        frmLogon.ShowDialog()

        If frmLogon.ActionCancelled = False Then
            ' user has logged in
            If CurrentGame.selectedPlayer.PlayerName = "<Moderator>" Then
                ToolBarEnablementLevel = EnablementLevel.ModeratorLoggedIn
            Else
                ToolBarEnablementLevel = EnablementLevel.PlayerLoggedIn
                fmvMap.ShowMapOnly = False
            End If
        End If

    End Sub

    Private Sub btnDeploy_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDeploy.Click

        DeployUnit = Not DeployUnit

    End Sub

    Private Function CheckForUnresolvedCombats(ByRef allPlayersComplete As Boolean) As Boolean
        ' returns if there are unresolved combats
        ' the all players complete parameter determines if the End of combat screen should be shown.
        Dim batt As Battle
        Dim battKey As String
        Dim bUnresolvedRemaining As Boolean = False

        For Each battKey In CurrentGame.Battles_g.HT.Keys
            batt = CurrentGame.Battles_g.Item(battKey)
            If batt.BattleResult = BattleResult_cgd.NotFinished Then
                bUnresolvedRemaining = True
                Exit For
            End If
        Next

        ' default to all players complete
        allPlayersComplete = True

        If bUnresolvedRemaining = True Then
            Dim play As Player
            Dim playKey As String
            For Each playKey In CurrentGame.Players.Keys
                play = CurrentGame.Players.Item(playKey)
                If Not play.PlayerName = "<Moderator>" Then
                    If play.TurnComplete = False Then
                        allPlayersComplete = False
                        Exit For
                    End If
                End If
            Next
        End If

        Return bUnresolvedRemaining

    End Function


    Private Sub chiSelected_ShowRuleRange(ByVal ru As Rule) Handles chiSelected.ShowRuleRange
        Try
            '    Dim obj As ChitMember
            'Dim ruleT As New RuleType
            '   obj = fmvMap2.SelectedChit
            'ruleT = CurrentGame.RuleTypes_g.Item(ruleTypeKey)
            'TASK: pixels per one mile from map data.
            '  Dim pixelsPerOneMile As Integer = fmvMap2.FMPData.MapScale.PixelCount / fmvMap2.FMPData.MapScale.MilesPerPixelCount

            'TASK: draw rule range for selected chit
            ' fmvMap2.DrawSingleRuleRange(True, ru.ptrRule.BasicRange * pixelsPerOneMile, obj.Location)
        Catch ex As Exception
            HandleException(c_Module, ex)
        End Try

    End Sub


    Private Function CalculateAverageMaxPV(ByVal GCClass As GroundChitClass_cgd) As Int32
        'Dim gcKey As String
        'Dim gc As GroundChitType
        Dim gcCount As Int16
        Dim totalPV As Int32
        Dim calculatedAverage As Int32

        Try
            For Each mem As ChitMember In CurrentGame.Chits
                If mem.UnitType = GroundChitClass_cgd.Battlegroup Then
                    gcCount += 1
                    totalPV += DirectCast(mem, BattlegroupChit).deployedpointvalue
                End If

            Next

            If gcCount <> 0 Then
                If totalPV <> 0 Then
                    calculatedAverage = totalPV / gcCount
                End If
            End If
        Catch ex As Exception
            HandleException(c_Module, ex)
        End Try

        Return calculatedAverage
    End Function

    Private Function CalculateMaxDeployedPV(ByVal GCClass As GroundChitClass_cgd) As Int32
        'Dim gcKey As String
        Dim gc As GroundChitType
        Dim maxPV As Int32

        For Each mem As ChitMember In CurrentGame.Chits
            If mem.UnitType = GroundChitClass_cgd.Battlegroup Then
                If maxPV < DirectCast(mem, BattlegroupChit).deployedpointvalue Then maxPV = DirectCast(mem, BattlegroupChit).deployedpointvalue
            End If
        Next

        Return maxPV
    End Function

    Private Sub CalculateCurrentDeployedPV()
        'Dim gc As GroundChitType
        'Dim gcKey As String
        Dim fact As Faction
        Dim factKey As String
        Dim dep As Long
        'Dim un As UnitType

        Try
            For Each factKey In CurrentGame.Faction_g.HT.Keys
                fact = CurrentGame.Faction_g.Item(factKey)

                For Each mem As ChitMember In CurrentGame.Chits

                    If mem.OwningFaction.Equals(fact) Then
                        If mem.UnitType = GroundChitClass_cgd.Battlegroup Then
                            If Not mem.Status = GroundUnitStatus_cgd.Dead Then dep += DirectCast(mem, BattlegroupChit).CurrentPV
                        End If
                    End If
                Next

                fact.FactionDeployedPoints = dep
                dep = 0
            Next

        Catch ex As Exception
            HandleException(c_Module, ex)
        End Try

    End Sub

    Private Sub btnChitManager_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnChitManager.Click
        Try
            '    Dim frmMan As New frmManager(CurrentGame)
            '   frmMan.ShowDialog()
            MessageBox.Show("That functionality is being redesigned.", "Unavailable Functionality")
        Catch ex As Exception
            HandleException("btnChitManager.Click", ex)
        End Try
    End Sub

    Private Sub chiSelected_ResourceSelected(ByVal res As ResourcePoolItem) Handles chiSelected.ResourceSelected
        ' this means a resource has been selected for consumption (from the selected objective)
        Try
            'TASK: Resource selected for consumption?
            'Dim inst As InstallationChit = DirectCast(fmvMap2.SelectedChit, InstallationChit)
            'Dim frmConsume As New frmConsumeResource(res, CurrentGame)
            'frmConsume.ShowDialog()
            'chiSelected.ShowSelectedChitProperties(fmvMap2.SelectedChit, CurrentGame)

        Catch ex As Exception
            HandleException(c_Module, ex)
        End Try
    End Sub

    Private Sub chiSelected_ShowRuleDetails(ByVal ru As Rule) Handles chiSelected.ShowRuleDetails
        Dim frmRuleInfo As New frmBasicInfoBox(ru.ptrRule)
        frmRuleInfo.ShowDialog()

    End Sub

    Private Sub chiSelected_ShowResourceDetails(ByVal res As ResourcePoolItem) Handles chiSelected.ShowResourceDetails
        Dim frmResInfo As New frmBasicInfoBox(res.resourceTypeptr)
        frmResInfo.ShowDialog()
    End Sub


    Private Sub pnlShowBattles_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles pnlShowBattles.Click
        eveEventList.Visible = False
        bttBattles.Visible = True
        mssCenter.Visible = False
    End Sub

    Private Sub pnlShowEventLog_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles pnlShowEventLog.Click
        eveEventList.Visible = True
        bttBattles.Visible = False
        mssCenter.Visible = False
    End Sub

    Private Sub pnlShowMessageCenter_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles pnlShowMessageCenter.Click
        eveEventList.Visible = False
        bttBattles.Visible = False
        mssCenter.Visible = True
    End Sub

#Region "Combat Panel Actions"
    '    Private Sub lstCombats_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
    '        ' list the combat info
    '        Try
    '            ptrSelectedBattle = lstCombats.SelectedItem
    '            ShowChitsInDirectCombat()
    '            ' don't forget rules and such :D
    '            ShowAvailableRules()
    '            ShowAvailableReinforcementChits()
    '        Catch ex As Exception
    '            HandleException(c_Module, ex)
    '        End Try
    '    End Sub

    '    Private Sub ShowChitsInDirectCombat()
    '        ' shows ALL chits involved in contact combat, not those that are within reinforcement range.
    '        If (ptrSelectedBattle Is Nothing) Or (CurrentGame.selectedPlayer Is Nothing) Then Exit Sub

    '        Dim key As String
    '        Dim GndChit As GroundChitType

    '        tvwInvolvedChits.Nodes.Clear()

    '        ' HACK: only considers two opposing factions
    '        For Each key In ptrSelectedBattle.InvolvedChits.Keys
    '            Dim nod As New TreeNode
    '            GndChit = ptrSelectedBattle.InvolvedChits.Item(key)
    '            ' only list units in direct combat. Those units selected as reinforcing are listed in another box.
    '            nod.Text = GndChit.Name & " [" & GndChit.CurrentPointValue & "]"
    '            If (CampaignerGameData.CDGKEY_FACTION & GndChit.OwningFaction) = CurrentGame.selectedPlayer.FactionKey Then
    '                nod.ForeColor = Color.DarkGreen
    '            Else
    '                nod.ForeColor = Color.DarkRed
    '            End If
    '            tvwInvolvedChits.Nodes.Add(nod)
    '            If GndChit.GroundChitClass = GroundChitClass_cgd.Objective Then
    '                ' add some info about this objective in the objectivetreeview
    '                Dim obj As cmplib01.ObjectiveType
    '                obj = GndChit
    '                ' list properties
    '                nod.ImageIndex = 0
    '            ElseIf GndChit.GroundChitClass = GroundChitClass_cgd.Unit Then
    '                Dim unit As cmplib01.UnitType
    '                unit = GndChit
    '                ' list properties
    '                nod.ImageIndex = 1
    '            ElseIf GndChit.GroundChitClass = GroundChitClass_cgd.Token Then
    '                Dim tok As cmplib01.TokenType
    '                tok = GndChit
    '                ' list properties
    '                nod.ImageIndex = 2
    '            End If

    '        Next

    '    End Sub

    '    Private Sub ShowAvailableReinforcementChits()
    '        ' lists for the player chits that are within reinforcement range of this battle (a property of campaignergamedata)
    '        ' and their current assignment status (reinforceing, ok, etc) Only units with a status of OK can be assigned as reinforcements.
    '        ' units that are already reinforcing this battle are marked with a check. 
    '        ' unchecking a unit marks this unit as no longer supporting the combat, and when the player selects 'Assign', his choices
    '        ' will be set and any UNCHECKED units will be removed from the battle if they exist, while CHECKED units will be added
    '        ' if they don't already exist.
    '        If (ptrSelectedBattle Is Nothing) Or (CurrentGame.selectedPlayer Is Nothing) Then Exit Sub

    '        Dim key As String
    '        Dim unit As UnitType
    '        Dim gc As GroundChitType

    '        If tvwReinforcements.Nodes.Count > 0 Then tvwReinforcements.Nodes.Clear()

    '        ' CLEANUP: break this out from so many if...end if blocks
    '        For Each key In CurrentGame.AllChits.Keys
    '            gc = CurrentGame.AllChits.Item(key)
    '            If gc.GroundChitClass = GroundChitClass_cgd.Unit Then
    '                unit = gc
    '                If unit.OwningPlayer = CurrentGame.selectedPlayer.PlayerID Then
    '                    ' check status. Check distance. If the unit is already engaged in combat, or is supporting another unit, its not listed. 
    '                    If (unit.Status = GroundUnitStatus_cgd.OK) Or (unit.Status = GroundUnitStatus_cgd.Moving) Then
    '                        If WithinReinforcementRange(unit.Location, ptrSelectedBattle.BattleLocation) = True Then
    '                            Dim node As New TreeNode(unit.Name)
    '                            node.Tag = unit.Key
    '                            tvwReinforcements.Nodes.Add(node)
    '                        End If
    '                    ElseIf unit.Status = GroundUnitStatus_cgd.Reinforcing Then
    '                        ' check to see if this unit is reinforcing the SELECTED BATTLE
    '                        If unit.BattleInvolvedInID = ptrSelectedBattle.BattleID Then
    '                            Dim node As New TreeNode(unit.Name)
    '                            node.Tag = unit.Key
    '                            node.Checked = True
    '                            tvwReinforcements.Nodes.Add(node)
    '                        End If
    '                    End If
    '                End If
    '            End If
    '        Next

    '    End Sub

    '    Private Function WithinReinforcementRange(ByRef location As Point, ByRef target As Point) As Boolean
    '        If XYDistance(location.X, target.X, location.Y, target.Y) <= CurrentGame.ReinforcementRange Then
    '            Return True
    '        Else
    '            Return False
    '        End If
    '    End Function

#Region "Select and Deselect Reinforcements"

    '    Private Sub AssignReinforcements()
    '        Dim nod As TreeNode
    '        Dim unit As UnitType

    '        For Each nod In tvwReinforcements.Nodes
    '            unit = CurrentGame.AllChits.Item(nod.Tag)
    '            If nod.Checked = True Then
    '                SelectReinforcement(unit)
    '            Else
    '                DeselectReinforcement(unit)
    '            End If
    '        Next

    '    End Sub

    '    Private Sub SelectReinforcement(ByRef unit As UnitType)
    '        ' Ok, if the unit isn't already listed as reinforcing this combat, add it.
    '        If unit.CurrentBattlePosture = BattlePosture_cgd.NoBattle Then
    '            If ActivePlayerPOV() = PlayerPOV_cgd.Attacking Then
    '                unit.CurrentBattlePosture = BattlePosture_cgd.AttackingSupport
    '                unit.BattleInvolvedInID = ptrSelectedBattle.BattleID
    '                unit.Status = GroundUnitStatus_cgd.Reinforcing
    '                ' add to the battle involvedchits
    '                ptrSelectedBattle.InvolvedChits.Add(unit.Key, unit)
    '            Else
    '                unit.CurrentBattlePosture = BattlePosture_cgd.Defending
    '                unit.BattleInvolvedInID = ptrSelectedBattle.BattleID
    '                unit.Status = GroundUnitStatus_cgd.Reinforcing
    '                ' add to the battles involvedchits
    '                ptrSelectedBattle.InvolvedChits.Add(unit.Key, unit)
    '            End If
    '        End If
    '    End Sub

    '    Private Sub DeselectReinforcement(ByRef unit As UnitType)
    '        ' if the unit is listed as reinforcing, remove it
    '        If unit.CurrentBattlePosture <> BattlePosture_cgd.NoBattle Then
    '            unit.CurrentBattlePosture = BattlePosture_cgd.NoBattle
    '            unit.BattleInvolvedInID = -1
    '            unit.Status = GroundUnitStatus_cgd.OK
    '            ptrSelectedBattle.InvolvedChits.Remove(unit.Key)
    '        End If
    '    End Sub

#End Region

    '    Private Sub tvwReinforcements_AfterCheck(ByVal sender As System.Object, ByVal e As System.Windows.Forms.TreeViewEventArgs)
    '        AssignReinforcements()
    '    End Sub

    '    Private Sub ShowAvailableRules()
    '        ' this displays the rules available to the player that are in RANGE of the BATTLE (not specific chits)
    '        Dim gcKey As String
    '        Dim rulKey As String
    '        Dim gc As GroundChitType
    '        Dim rulet As RuleType
    '        Dim rulie As Rule
    '        Dim ruleOK As Boolean
    '        Dim ownerOK As Boolean
    '        Dim factKey As String

    '        If tvwAssignedRules.Nodes.Count > 0 Then
    '            tvwAssignedRules.Nodes.Clear()
    '        End If

    '        For Each gcKey In CurrentGame.AllChits.Keys
    '            Dim ruleAssignedThisCombat As Boolean = False

    '            gc = CurrentGame.AllChits.Item(gcKey)
    '            ' check to make sure this player can assign this rule
    '            ownerOK = False
    '            If gc.GroundChitClass = GroundChitClass_cgd.Objective Then
    '                factKey = CurrentGame.CDGKEY_FACTION & gc.OwningFaction
    '                If factKey = CurrentGame.selectedPlayer.FactionKey Then ownerOK = True
    '            Else
    '                If gc.OwningPlayer = CurrentGame.selectedPlayer.PlayerID Then ownerOK = True
    '            End If

    '            ' check all rules for this chit and see which ones are in range 
    '            If ownerOK Then
    '                For Each rulie In gc.GCRules
    '                    ' default ruleOK to false
    '                    ruleOK = False
    '                    rulet = CurrentGame.RuleTypes_g.Item(CampaignerGameData.CDGKEY_RULETYPE & rulie.ruleTypeID)
    '                    If rulet.AppliesDuring <> RuleApplies_cgd.NonCombat Then
    '                        ' it applies either during combat, or always, so, check other values

    '                        If rulie.currentUses = 1 Then     ' this is how many uses are REMAINING... duh... stupid name.
    '                            ruleOK = True
    '                        Else
    '                            ' this rule is assigned somewhere. Is it assigned HERE? In this very battle?
    '                            ruleOK = False
    '                            If rulie.battleAssignedTo = ptrSelectedBattle.BattleID Then
    '                                ruleAssignedThisCombat = True
    '                            End If
    '                        End If
    '                        ' if the rule is ok for both applies during and available uses, we'll check range

    '                        If ruleOK Then
    '                            If XYDistance(gc.Location.X, ptrSelectedBattle.BattleLocation.X, gc.Location.Y, ptrSelectedBattle.BattleLocation.Y) <= (rulet.BasicRange * fmvmap2.FMPData.PixelsPerOneMile) Then
    '                                ' add the rule to the list
    '                                AddAvailableRule(rulet, gcKey)
    '                            End If
    '                        Else ' the rule is NOT ok... meaning its currentuses is set to 1.
    '                            ' the rule is assigned to SOMETHING, either in this battle or a different battle.
    '                            ' if the rule is assigned to this battle, AddAvailable with the check already set... otherwise
    '                            ' add this rule with a checkmark. :P
    '                            If ruleAssignedThisCombat = True Then
    '                                AddAvailableRule(rulet, gcKey, True)
    '                            End If
    '                        End If
    '                    End If
    '                Next

    '            End If

    '        Next

    '    End Sub

    '    Private Sub AddAvailableRule(ByRef ruleT As RuleType, ByVal owningChitKey As String, Optional ByVal withCheck As Boolean = False)
    '        Dim gc As GroundChitType = CurrentGame.AllChits(owningChitKey)
    '        Dim ruleTypeNode As New ChitRuleTreeNode("[" & gc.Name & "] " & ruleT.RuleName, owningChitKey, ruleT.RuleTypeID)

    '        If withCheck = True Then
    '            ruleTypeNode.Checked = True
    '        End If

    '        tvwAssignedRules.Nodes.Add(ruleTypeNode)

    '    End Sub

    '    Private Function HasThisRule(ByVal ruleT As RuleType) As Boolean
    '        Dim asgnRule As AssignedRule
    '        Dim asgnRuleKey As String

    '        If ActivePlayerPOV() = PlayerPOV_cgd.Attacking Then
    '            For Each asgnRuleKey In ptrSelectedBattle.AttackerAssignedRules.Keys
    '                asgnRule = ptrSelectedBattle.AttackerAssignedRules.Item(asgnRuleKey)
    '                If asgnRule.RuleKey = ruleT.Key Then
    '                    Return True
    '                End If
    '            Next
    '        Else
    '            For Each asgnRuleKey In ptrSelectedBattle.DefenderAssignedRules.Keys
    '                If asgnRuleKey = ruleT.Key Then
    '                    Return True
    '                End If
    '            Next
    '        End If
    '        ' if nothing found...
    '        Return False
    '    End Function

#End Region

    Private Function ActivePlayerPOV() As PlayerPOV_cgd
        If CurrentGame.selectedPlayer.FactionKey = CampaignerGameData.CDGKEY_FACTION & ptrSelectedBattle.AttackingFactionID Then
            Return PlayerPOV_cgd.Attacking
        Else
            Return PlayerPOV_cgd.Defending
        End If
    End Function

    Private Sub tvwAssignedRules_AfterCheck(ByVal sender As System.Object, ByVal e As System.Windows.Forms.TreeViewEventArgs)
        ' examine the check status
        Dim ruleNode As ChitRuleTreeNode = e.Node
        If ruleNode.Checked = True Then
            SelectRule(ruleNode)
        Else
            DeselectRule(ruleNode)
        End If
    End Sub

#Region "Select and Deselect Rules"
    Private Sub SelectRule(ByVal chRule As ChitRuleTreeNode)
        ' examines the chitruletreenode and extracts information required
        'Dim gc As GroundChitType

        'Try
        '    '   gc = CurrentGame.AllChits.Item(chRule.ChitKey)
        '    ' select this rule and set his availability to 0.
        '    ' the last parameter refers to the rule's currentuses... which is how many uses remain for the rule.
        '    DecrementIncrementRuleForUse(chRule, chRule, True)
        '    ' now... set this rule's battleassignedto property to the selected battle
        '    AssignRuleToBattle(chRule)
        'Catch argEx As ArgumentException
        '    ' this means that most likely the rule type has already been assigned, so we need to boost the count
        '    ' not really because I changed this functionality.

        'Catch ex As Exception
        '    HandleException(c_Module, ex)
        'End Try

    End Sub

    Private Sub DeselectRule(ByVal chRule As ChitRuleTreeNode)
        ' examines the selected assignedRule object in lstAssignedRules and removes the event from
        ' the battle, as well as incrementing the rule available uses if required.

        ' find the rule in the correct chit and set its currentuses to 0
        'Dim gc As GroundChitType
        'Try
        '    gc = CurrentGame.AllChits.Item(chRule.ChitKey)
        '    ' the last parameter refers to the rule's currentuses... which is how many uses remain for the rule.
        '    DecrementIncrementRuleForUse(gc, chRule.RuleTypeID, False)
        '    DeassignRuleToBattle(chRule)
        'Catch ex As Exception
        '    HandleException(c_Module, ex)
        'End Try

    End Sub

    Private Sub DecrementIncrementRuleForUse(ByRef gc As GroundChitType, ByVal ruleTypeID As Int32, ByVal setCurrentToZero As Boolean)
        ' examine the chit's rule current and max uses and reduce one if required
        'Dim tok As TokenType
        'Dim chitRule As Rule
        'Dim ruleT As RuleType

        '' find the rule in this chit's list
        'Dim ruleKey As String
        'Dim gcRule As Rule
        'For Each gcRule In gc.GCRules
        '    If gcRule.ruleTypeID = ruleTypeID Then
        '        ' if the rule type id's match, reduce the use count
        '        If setCurrentToZero = True Then
        '            gcRule.currentUses = 0
        '            gcRule.battleAssignedTo = ptrSelectedBattle.BattleID
        '        Else
        '            gcRule.currentUses = 1
        '            gcRule.battleAssignedTo = -1
        '        End If
        '        Exit For
        '    End If
        'Next
    End Sub

    Private Sub DeassignRuleToBattle(ByVal chrule As ChitRuleTreeNode)
        Dim HT As Hashtable

        'If ActivePlayerPOV() = PlayerPOV_cgd.Attacking Then
        '    HT = ptrSelectedBattle.AttackerAssignedRules
        'Else
        '    HT = ptrSelectedBattle.DefenderAssignedRules
        'End If

        'Try
        '    Dim asgn As AssignedRule
        '    Dim asgnKey As String
        '    For Each asgnKey In HT.Keys
        '        asgn = HT.Item(asgnKey)
        '        If chrule.RuleTypeID = asgn.RuleKey Then
        '            If asgn.Count = 1 Then
        '                HT.Remove(asgnKey)
        '            Else
        '                asgn.Count -= 1
        '            End If
        '            Exit For
        '        End If
        '    Next
        'Catch ex As Exception
        '    HandleException(c_Module, ex)
        'End Try

    End Sub

    Private Sub AssignRuleToBattle(ByVal chrule As ChitRuleTreeNode)
        'Dim HT As Hashtable

        'If ActivePlayerPOV() = PlayerPOV_cgd.Attacking Then
        '    HT = ptrSelectedBattle.AttackerAssignedRules
        'Else
        '    HT = ptrSelectedBattle.DefenderAssignedRules
        'End If

        '' try to add the rule. If it FAILZ then... welllllll, there is already a rule of this type in the collection. So... bump its count.
        'Try
        '    Dim asgn As New AssignedRule
        '    asgn.BattleAssignedTo = ptrSelectedBattle.BattleID
        '    asgn.DisplayName = chrule.Text
        '    asgn.OwningChitKey = chrule.ChitKey
        '    asgn.RuleKey = "RULT" & chrule.RuleTypeID
        '    asgn.Count = 1
        '    HT.Add("RULT" & chrule.RuleTypeID, asgn)
        'Catch argEx As ArgumentException
        '    ' the type is already there. Bump the count by one
        '    HT.Item("RULT" & chrule.RuleTypeID).count += 1
        'Catch ex As Exception
        '    HandleException(c_Module, ex)
        'End Try

    End Sub

#End Region

    Private Sub casAssets_InstallationSelected(ByRef obj As InstallationChit) Handles casAssets.InstallationSelected
        'fmvMap2.SelectedChit = obj
        'fmvMap2.RedrawMap()
        'TASK: select unit from assets
    End Sub

    Private Sub casAssets_UnitSelected(ByRef unit As BattlegroupChit) Handles casAssets.UnitSelected
        'fmvMap2.SelectedChit = unit
        'fmvMap2.RedrawMap()
        'TASK: select unit from assets
    End Sub

    Private Sub newTurnGrinder_PercentComplete(ByVal percent As Integer) Handles newTurnGrinder.PercentComplete
        Me.Text = "Campaigner :Processing Turn [" & percent & "%]"
        If percent = 100 Then
            Me.Text = "Campaigner"
        End If
    End Sub

    Private Sub btnVictory_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnVictory.Click
        If CurrentGame.selectedFaction Is Nothing Then Exit Sub

        Dim fVictory As New frmVictoryConditions
        fVictory.Victory = CurrentGame.selectedFaction.FactionVictoryConditions

        fVictory.ShowDialog()
    End Sub

    Private Sub pnlMainClient_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles pnlMainClient.Paint
        If mTurnMode = TurnMode.CombatTurn Then
            PaintDanger(pnlMainClient)
        End If
    End Sub

    Private Sub eocCombatResolution_ApplyCombatResults() Handles eocCombatResolution.ApplyCombatResults
        ' the stinking turn is finally over!!
        ApplyCombatResults()
        'hide the combat thingie
        eocCombatResolution.Visible = False
        ResetPlayerComplete()
    End Sub

    Private Sub fmvMap_chitSelected(ByRef member As cmplib01.ChitMember) Handles fmvMap.chitSelected
        chiSelected.ShowSelectedChitProperties(fmvMap.SelectedChit, Me.CurrentGame)
    End Sub

    Private Sub fmvMap_chitUnselected() Handles fmvMap.chitUnselected
        chiSelected.ShowSelectedChitProperties(Nothing, CurrentGame)
    End Sub


    Private Sub fmvMap_waypointChange() Handles fmvMap.waypointChange
        '// reselect the chit
        chiSelected.ShowSelectedChitProperties(fmvMap.SelectedChit, Me.CurrentGame)
        fmvMap.RedrawAndRender()
    End Sub

    Private Sub btnResources_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnResources.Click
        If m_ToolBarEnablementLevel = EnablementLevel.PlayerLoggedIn Then
            Dim fRes As New frmResourceManager
            fRes.ShowDialog(CurrentGame)
        End If
    End Sub
End Class
